package Day020_NIO_AIO.demo2_NIO2_AIO.Test1_AIO同步连接同步读取数据;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Future;

/**
 * @author zhangyan
 * @date 2020/5/13 14:06
 */
//没有意义

public class Server {
    public static void main(String[] args) throws Exception{

        //1. 获取服务器通道对象
        AsynchronousServerSocketChannel assc = AsynchronousServerSocketChannel.open();

        //2. 对象调用bind()方法 绑定团口号
        assc.bind(new InetSocketAddress(666));

        System.out.println(1);
        //3. accept()同步的方法,等待接收请求
        //以前是直接返回客户端通道,现在是吧accept()方法的客户端对象封装到一个Future对象中
        Future<AsynchronousSocketChannel> future1 = assc.accept();
        //获取Future中封装的客户端通道对象(future不能调用read方法)
        AsynchronousSocketChannel asc = future1.get();

        System.out.println(2);
        //4. 使用客户端通道对象读取数据
        //同步读数据
        //创建ByteBuffer缓冲数组
        ByteBuffer b = ByteBuffer.allocate(1024);
        //以前返回的是读取的字节个数,现在是读取到的字节个数封装到Future对象中
        Future<Integer> future2 = asc.read(b);
        //获取字节个数
        Integer len = future2.get();
        //打印数据
        System.out.println(new String(b.array(),0,len));
        System.out.println(3);

        //5. 关闭资源
        asc.close();

    }
}
